<template>
    <el-dialog v-model="visible" title="重置密码" width="409px">
        <template #header>重置密码</template>
        <el-form ref="pwdFormRef" :model="ruleForm" :rules="rules" :size="formSize" label-width="auto">
            <el-form-item label="密码" prop="password">
                <el-input v-model="ruleForm.password" placeholder="请输入密码" clearable />
            </el-form-item>
        </el-form>
        <template #footer>
            <span class="dialog-footer">
                <el-button size="default" @click="onCancel">取 消</el-button>
                <el-button type="primary" size="default" @click="onSubmit(pwdFormRef)">保 存</el-button>
            </span>
        </template>
    </el-dialog>
</template>
<script lang="ts" setup>
import { ref, reactive } from 'vue'
import { ElMessage } from 'element-plus'
import { User } from '@/api/system/user/types.ts'
import { updatePassword } from '@/api/system/user/index.ts'
import type { ComponentSize, FormInstance, FormRules } from 'element-plus'

const visible = ref(false)
const pwdFormRef = ref()
const formSize = ref<ComponentSize>('default')
const rules = reactive<FormRules<User.Password>>({
    password: [{ required: true, message: '请输入密码', trigger: 'blur' }],
})
/** 表单对象 */
const ruleForm = reactive<User.Password>({})

/** 关闭弹窗 */
const onCancel = () => {
    visible.value = false
}

/** 修改密码 */
const onSubmit = async (formEl: FormInstance | undefined) => {
    if (!formEl) return
    await formEl.validate((valid, fields) => {
        if (valid) {
            updatePassword(ruleForm)
                .then((resp) => {
                    console.log(resp)
                    onCancel()
                    ElMessage.success('修改成功')
                })
                .catch(() => {
                    ElMessage.error('修改失败')
                })
        } else {
            console.log('error submit!', fields)
        }
    })
}
/** 打开弹窗 */
const openDialog = (item: User.Row) => {
    ruleForm.userId = item.id
    visible.value = true
}

defineExpose({
    openDialog,
})
</script>
